package cn.wit.summit.chwan.widgets;

import android.content.Context;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import cn.wit.summit.chwan.Stat.StatFactory;
import cn.wit.summit.chwan.models.dbmanager.DownloadTaskManager;
import cn.wit.summit.chwan.models.dto.GameListBaseBean;
import cn.wit.summit.chwan.models.response.IndexBeanV3Response;
import cn.wit.summit.chwan.tools.downloadtool.DownLoadStatusConfig;
import cn.wit.summit.chwan.ui.base.PermissionBaseActivity;
import cn.wit.summit.chwan.utils.APKUtils;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.tools.downloadtool.DownloadTool;
import cn.wit.summit.chwan.utils.IntentUtil;
import cn.wit.summit.chwan.utils.LogUtils;
import cn.wit.summit.chwan.utils.ToastUtils;
import cn.wit.summit.chwan.utils.UtilsMy;

import cn.wit.summit.chwan.R;


/**
 * Created by pengsk on 2017/10/30.
 */

public class DownloadViewStroke extends LinearLayout implements View.OnClickListener {
    private TextView instalButtomButn;
    private TextView moneyText;
    //    private PayTagInfo payTagInfo;
    private int down_status;
    private IndexBeanV3Response.CreditInfoBean credit_info;

    public DownloadViewStroke(Context context) {
        super(context);
        initView(context);
    }

    public DownloadViewStroke(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public DownloadViewStroke(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    private void initView(Context context) {
        View view = LayoutInflater.from(context).inflate(R.layout.install_button_stroke_layout, this);
        instalButtomButn = (TextView) view.findViewById(R.id.instalButtomButn);
        moneyText = (TextView) view.findViewById(R.id.moneyText);
    }

    private String gameId;
    private DownLoadTaskTable downloadTask;

    public void initData(GameListBaseBean gameListBaseBean) {
        try {
            credit_info = gameListBaseBean.getCredit_info();
//        setCoin(tipNew, downloadTask);
            this.gameId = gameListBaseBean.getGame_id();
//        this.payTagInfo = payTagInfo;
            this.downloadTask = gameListBaseBean.getTaskTable();
//            LogUtils.e("DownStatues initdata "+downloadTask.getDownStatus());
            DownLoadTaskTable taskTable = DownloadTaskManager.getInstance().findByGameId(gameId);
            if (taskTable != null) {
                this.downloadTask = taskTable;
                LogUtils.e("DownStatues  initdata2-1 "+downloadTask.getDownStatus());

            } else if (downloadTask == null) {
                this.downloadTask = gameListBaseBean.getDownloadTaskTableSimple();
            }
            gameListBaseBean.setTaskTable(downloadTask);
            this.down_status = downloadTask.getDownStatus();
            instalButtomButn.setOnClickListener(this);
            updateButn(downloadTask);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void initUpdateData(GameListBaseBean gameListBaseBean) {
        try {
//        setCoin(tipNew, downloadTask);
            this.gameId = gameListBaseBean.getGame_id();
//        this.payTagInfo = payTagInfo;
            this.downloadTask = gameListBaseBean.getTaskTable();
//            DownLoadTaskTable taskTable= DownloadTaskManager.getInstance().findByGameId(gameId);
//            if (taskTable!=null){
//                this.downloadTask=taskTable;
//            }else
            if (downloadTask == null) {
                this.downloadTask = gameListBaseBean.getDownloadTaskTableSimple();
            }
            gameListBaseBean.setTaskTable(downloadTask);
            this.down_status = downloadTask.getDownStatus();
            instalButtomButn.setOnClickListener(this);
            updateButn(downloadTask);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//
//    public void setCoin(TipNew tipNew, DownloadTask downloadTask) {
//        setCoin(tipNew, this, downloadTask);
//    }

    //    void setCoin(TipNew showTip, View convertView, DownloadTask downloadTask) {
//        TextView tongban;
//        if (convertView instanceof TextView) {
//            tongban = (TextView) convertView;
//        } else {
//            tongban = (TextView) convertView.findViewById(R.id.moneyText);
//
//        }
//        if (tongban == null) return;
//        if (downloadTask != null && downloadTask.getStatus() != DownLoadStatusConfig.STATUS_NORMAL) {
//            tongban.setVisibility(View.INVISIBLE);
//            return;
//        }
//        if (showTip != null && showTip.getCoin() != null) {
//            tongban.setText(showTip.getCoin().getName());
//            tongban.setVisibility(View.VISIBLE);
//        } else {
//            tongban.setVisibility(View.INVISIBLE);
//        }
//    }
    public void setProgress(int progress) {
        instalButtomButn.setText(progress + "%");
    }

    public void updateButn(DownLoadTaskTable downloadTask) {

        int status = 0;
        if (downloadTask != null) {
            boolean isInstall = APKUtils.getInstance(getContext()).checkInstall(getContext(), downloadTask.getPackageName());
            DownLoadTaskTable taskDb = DownloadTaskManager.getInstance().findByGameId(downloadTask.getGameId());
            if (isInstall && taskDb == null && downloadTask.getDownStatus() != DownLoadStatusConfig.UPDATE){
                downloadTask.setDownStatus(DownLoadStatusConfig.INSTALLED);
            }
            status = downloadTask.getDownStatus();
        }
        instalButtomButn.setBackgroundResource(R.drawable.installbutn_normal_butn);
        instalButtomButn.setTextColor(Color.parseColor("#72b0fd"));
        if (credit_info != null) {
            instalButtomButn.setText("详情");
            instalButtomButn.setTextColor(Color.parseColor("#262626"));
            instalButtomButn.setBackgroundResource(R.drawable.index_detail_selector);
        } else if (status == DownLoadStatusConfig.UPDATE) {
            instalButtomButn.setText("升级");

        } else if (status == DownLoadStatusConfig.UNZIP) {
            instalButtomButn.setText("解压中");
            instalButtomButn.setTextColor(Color.parseColor("#4bbd4e"));
            instalButtomButn.setBackgroundResource(R.drawable.installbutton_unziping_butn);
        } else if (status == DownLoadStatusConfig.UNZIP_ERROR||status==DownLoadStatusConfig.UNZIP_WAIT) {
            instalButtomButn.setText("解压");
            instalButtomButn.setTextColor(Color.WHITE);
            instalButtomButn.setBackgroundResource(R.drawable.installbutton_installandunzip_butn);
        } else if (status == DownLoadStatusConfig.INSTALL_WAIT) {
            instalButtomButn.setText("安装");
            instalButtomButn.setTextColor(Color.WHITE);
            instalButtomButn.setBackgroundResource(R.drawable.installbutton_installandunzip_butn);
        } else if (status == DownLoadStatusConfig.INSTALLING) {
            instalButtomButn.setText("安装中");
            instalButtomButn.setTextColor(Color.WHITE);
            instalButtomButn.setBackgroundResource(R.drawable.installbutton_installandunzip_butn);
        } else if (status == DownLoadStatusConfig.DOWNLOADING || status == DownLoadStatusConfig.START) {
            setProgress(downloadTask.getDownprogress());
            instalButtomButn.setTextColor(Color.parseColor("#70a4ff"));
            instalButtomButn.setBackgroundResource(R.drawable.installbutton_progress_butn);
        } else if (status == DownLoadStatusConfig.DOWNLOAD_STOP || status == DownLoadStatusConfig.DOWNLOAD_ERROR || status == DownLoadStatusConfig.DOWNLOAD_FINISH) {
            instalButtomButn.setText("继续");
            instalButtomButn.setTextColor(Color.parseColor("#43BEFE"));
        } else if (status == DownLoadStatusConfig.WAIT) {
            instalButtomButn.setText("等待");
        } else if (status == DownLoadStatusConfig.INSTALLED) {
            instalButtomButn.setTextColor(Color.parseColor("#72b0fd"));
            instalButtomButn.setBackgroundResource(R.drawable.installbutton_open_butn);
            instalButtomButn.setText("打开");
        } else {
            instalButtomButn.setText(instalButtomButn.getResources().getString(R.string.download_status_download));
            if (downloadTask != null) {
                UtilsMy.setButnStatus(instalButtomButn, downloadTask.getDownStatus(), downloadTask.getGameId());
            }
        }
    }


    public void instalButtomButnClicked(DownLoadTaskTable downloadTask) {

        int status = 0;
        if (downloadTask != null) {
            boolean isInstall = APKUtils.getInstance(getContext()).checkInstall(getContext(), downloadTask.getPackageName());
            DownLoadTaskTable taskDb = DownloadTaskManager.getInstance().findByGameId(downloadTask.getGameId());
            if (isInstall && taskDb == null && downloadTask.getDownStatus() != DownLoadStatusConfig.UPDATE)
                downloadTask.setDownStatus(DownLoadStatusConfig.INSTALLED);
            status = downloadTask.getDownStatus();

        }

        if (downloadTask == null) {
            UtilsMy.starServiceDownGame(getContext(), downloadTask.getGameId());
            StatFactory.getInstance().sendGameDownload(getContext(),downloadTask.getGameId(),3+"",false);
            return;
        } else if (downloadTask != null && (status == DownLoadStatusConfig.DOWNLOADING)) {
            DownloadTool.stopTask(downloadTask);
            StatFactory.getInstance().sendGameDownload(getContext(),downloadTask.getGameId(),4+"",false);
        } else if (status == DownLoadStatusConfig.UNZIP) {
            return;
        } else if (status == DownLoadStatusConfig.UNZIP_ERROR || status == DownLoadStatusConfig.UNZIP_WAIT) {
            StatFactory.getInstance().sendUnZip(getContext(),downloadTask.getGameId(),3+"");
            DownloadTool.unzip(getContext(), downloadTask);
            return;
        } else if (status == DownLoadStatusConfig.INSTALLED) {
            APKUtils.getInstance(getContext()).openThirdApp(getContext(), downloadTask.getPackageName(), downloadTask.getGameId());

        } else if (DownLoadStatusConfig.INSTALL_WAIT == status) {
            try {
                APKUtils.getInstance(getContext()).installAPK(getContext(), downloadTask.getDownPath(), downloadTask.getGameId());
            } catch (Exception e) {
                ToastUtils.getInstance(getContext()).showToastSystem("安装失败，请重新尝试！");
            }
        }
//        else if (status == DownLoadStatusConfig.UPDATE) {
//            if (downloadTask != null) {
//                DownloadTool.downloadGame(getContext(), downloadTask);
//            }
//        }
        else {
            if (downloadTask != null) {
//                StatFactory.getInstance().sendGameDownload(getContext(),downloadTask.getGameId(),3+"",false);
                DownloadTool.downloadGame(getContext(), downloadTask, credit_info);
            }
        }
        updateButn(downloadTask);
    }

    long clickTime = 0;

    @Override
    public void onClick(View view) {
        if (clickTime == 0 || System.currentTimeMillis() - clickTime > 2000) {
            if (credit_info==null) {
                clickTime=System.currentTimeMillis();
                instalButtomButnClicked(downloadTask);
            } else {
                IntentUtil.getInstance().goGamedetial((PermissionBaseActivity)getContext(), gameId, 1);
            }
        }
    }
}
